<template>
    <div>
        <PageHeader  v-if="!!title" :title="title" style="margin-bottom: 10px;" content="" hidden-breadcrumb/>
        <Form ref="form" v-if="showSearch && formRefresh" :model="queryFormData" :rules="rules" :label-width="labelWidth" :label-position="labelPosition">
            <Row :gutter="24" type="flex" justify="end">
                <Col v-for="(item,index) in queryFormItem" :key="index" v-bind="grid">
                    <FormItem :label="item.title" :prop="item.key" >
                        <Input v-if="['input','String','text','Input','string','Text'].includes(item.editor)" v-model="queryFormData[item.key]"></Input>
                        <InputNumber v-else-if="['int','number'].includes(item.editor)"  v-model="queryFormData[item.key]"></InputNumber>
                        <Checkbox  v-else-if="['check','Boolean','Check','boolean'].includes(item.editor)" v-model="queryFormData[item.key]"></Checkbox>
                        <DatePicker v-else-if="['date','Date'].includes(item.editor)" type="date" show-week-numbers  transfer format="yyyy-MM-dd" v-model="queryFormData[item.key]"></DatePicker>
                        <TimePicker v-else-if="['time','Time'].includes(item.editor)" type="time" show-week-numbers  transfer format="HH:mm:ss" v-model="queryFormData[item.key]"></TimePicker>
                        <DatePicker v-else-if="['datetime','Datetime','DateTime'].includes(item.editor)" type="datetime" show-week-numbers  transfer format="yyyy-MM-dd HH:mm:ss" v-model="queryFormData[item.key]"></DatePicker>
                        <Input v-else  v-model="queryFormData[item.key]" ></Input>
                    </FormItem>
                </Col>
                <template v-if="collapse">
                    <Col v-for="(item,index) in collapseFormItem" :key="index+item.key" v-bind="grid">
                        <FormItem :label="item.title" :prop="item.key">
                            <Input v-if="['input','String','text','Input','string','Text'].includes(item.editor)" v-model="queryFormData[item.key]"></Input>
                            <InputNumber v-else-if="['int','number'].includes(item.editor)"  v-model="queryFormData[item.key]"></InputNumber>
                            <Checkbox  v-else-if="['check','Boolean','Check','boolean'].includes(item.editor)" v-model="queryFormData[item.key]"></Checkbox>
                            <DatePicker v-else-if="['date','Date'].includes(item.editor)" type="date" show-week-numbers  transfer format="yyyy-MM-dd" v-model="queryFormData[item.key]"></DatePicker>
                            <TimePicker v-else-if="['time','Time'].includes(item.editor)" type="time" show-week-numbers  transfer format="HH:mm:ss" v-model="queryFormData[item.key]"></TimePicker>
                            <DatePicker v-else-if="['datetime','Datetime','DateTime'].includes(item.editor)" type="datetime" show-week-numbers  transfer format="yyyy-MM-dd HH:mm:ss" v-model="queryFormData[item.key]"></DatePicker>
                            <Input v-else  v-model="queryFormData[item.key]" ></Input>
                        </FormItem>
                    </Col>
                    <Col v-bind="grid"></Col>
                </template>
                <Col v-bind="grid" class="ivu-text-right">
                    <FormItem>
                        <Button type="primary" @click="handleSearch">查询</Button>
                        <Button class="ivu-ml-8" @click="handleReset">重置</Button>
                        <a v-font="14" class="ivu-ml-8" @click="collapse = !collapse">
                            <template v-if="!collapse">
                                展开 <Icon type="ios-arrow-down" />
                            </template>
                            <template v-else>
                                收起 <Icon type="ios-arrow-up" />
                            </template>
                        </a>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Button v-if="showAdd" type="primary" ghost icon="md-add" @click="handleOpenCreate">添加</Button>
        <Button v-if="showDel" @click="handleDeleteMultiple" type="error" ghost icon="md-trash" class="ivu-ml-8" v-show="selectedData.length">批量删除</Button>
        <div class="ivu-inline-block ivu-fr">
            <Dropdown @on-click="handleChangeTableSize" trigger="click">
                <Tooltip class="ivu-ml" content="密度" placement="top">
                    <i-link>
                        <Icon type="md-list" />
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
                    <DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
                    <DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
                </DropdownMenu>
            </Dropdown>
            <Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
                <i-link @click.native="handleFullscreen">
                    <Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'" />
                </i-link>
            </Tooltip>
            <Tooltip class="ivu-ml" content="刷新" placement="top">
                <i-link @click.native="handleRefresh">
                    <Icon custom="i-icon i-icon-refresh" />
                </i-link>
            </Tooltip>
            <Dropdown trigger="click">
                <Tooltip class="ivu-ml" content="列设置" placement="top">
                    <i-link>
                        <Icon type="md-options" />
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <div class="ivu-p-8">列展示</div>
                    <Divider size="small" class="ivu-mt-8 ivu-mb-8" />
                    <template v-for="item in columns">
                        <li class="ivu-dropdown-item" :key="item.title" v-if="item.title" @click="item.show = !item.show">
                            <Checkbox v-model="item.show"></Checkbox>
                            <span>{{ item.title }}</span>
                        </li>
                    </template>
                </DropdownMenu>
            </Dropdown>
        </div>
        <br>
        <Table
            ref="table"
            :data="data"
            :columns="tableColumns"
            v-bind="tableAttrs"
            class="ivu-mt"
            @on-row-click="handleClickRow"
            @on-sort-change="handleSortChange"
            @on-select="handleSelect"
            @on-select-cancel="handleSelectCancel"
            @on-select-all="handleSelectAll"
            @on-select-all-cancel="handleClearSelect">
            <template slot-scope="{ row }" slot="action">
                <div @click.stop.prevent>
                    <a type="text" @click="handleEdit(row[primaryKey])">编辑</a>
                    <Divider type="vertical" />
                    <a type="text" @click="handleDelete(row[primaryKey])">删除</a>
                </div>
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page v-if="showPage"
                :total="pageNation.total"
                :page-size-opts="pageSizeOpts"
                :current.sync="pageNation.pageNumber"
                show-total
                show-sizer
                show-elevator
                :page-size="pageNation.pageSize"
                @on-change="handleChangePage"
                @on-page-size-change="handleChangePageSize"/>
        </div>
        <Drawer
            :styles="drawer.styles"
            v-model="drawer.show"
            :title="drawer.type === 'edit' ? '编辑信息' : drawer.type === 'new' ? '添加信息' : '查看信息'"
            width="560"
            :before-close="handleCloseEdit"
            :transfer="false">
            <starForm v-if="refresh" ref="_frm"
                      :showBtn="false"
                      :data="formData"
                      :form="form"
                      :title="formTitle"
                      :titleStyle="formTitleStyle"
                      :formStyle="formStyle"
                      :fields="formFields"
                      @submit="handleDataSubmit"
                      :style="{width:'100%',height:'100%'}"></starForm>
            <div class="page-form-drawer-drawer-footer" v-if="drawer.type === 'edit'">
                <Button type="primary" @click="handleSubmitEdit" :loading="submitting">提交</Button>
            </div>
            <div class="page-form-drawer-drawer-footer" v-if="drawer.type === 'new'">
                <Button type="primary" @click="handleSubmitNew" :loading="submitting">提交</Button>
            </div>
        </Drawer>
    </div>
</template>
<script>
import { cloneDeep,pick } from 'lodash';
export default {
    data(){
        return{
            //查询form开始
            grid: {
                xl: 8,
                lg: 8,
                md: 12,
                sm: 24,
                xs: 24
            },
            collapse: false,
            queryFormData:{},
            queryFormItem:[],
            collapseFormItem:[],
            rules: {},
            formRefresh:false,
            //查询form结束
            refresh:false,
            tableFullscreen: false,
            tableSize: '',
            columns: [],
            loading: false,
            selectedData: [],
            pageSizeOpts:[10,30,50,100],
            pageNation:{total:0,pageSize:10,pageNumber:1},
            submitting: false,
            starFormReady: true,
            formDataString:'',
            drawer: {
                show: false,
                type: 'edit', // edit || read || new
                styles: {
                    height: 'calc(100% - 55px)',
                    overflow: 'auto',
                    paddingBottom: '53px',
                    position: 'static'
                }
            },
            //默认表单配置
            starFormConfig:{
                title:'test',
                titleStyle:{},
                formStyle:{height:'100%',flex:'1 1 auto'},
                labelWidth:120,
                interval:'24px',
                itemWidth:null,
                itemAlign:true,
                col:1,
                disabled:false,
                fields:[]
            },

            form:{
                labelWidth:160,
                interval:'24px',
                itemWidth:null,
                itemAlign:true,
                col:2,
                disabled:false
            },
            formTitle:'',
            formTitleStyle:{},
            formStyle:{},
            formFields:[],

            //初始化原表单数据
            sourceFormData:{},
            //当前表单数据
            formData:{},
            selectedDataId:'',
            filterValue:{},
            primaryKey:'',
        }
    },
    props:{
        data: {
            default: () => {
                return []
            }
        },
        title:{
            default:()=>{
                return ''
            }
        },
        showAdd:{
            default:()=>{
                return true
            }
        },
        showDel:{
            default:()=>{
                return true
            }
        },
        showSearch:{
            default:()=>{
                return true
            }
        },
        showPage:{
            default:()=>{
                return true
            }
        },
        showDetail: {
            default: () => {
                return true
            }
        },
        formConfig:{
            default:()=>{
                return{}
            }
        },
        tableConfig:{
            default:()=>{
                return{}
            }
        }
    },
    created(){

    },
    mounted(){
        //初始化表格列
        this.initTableColumns();
        //初始化starForm编辑表单数据
        this.initStarFormConfig();
        //初始化查询form表单数据
        this.initQueryFormData();
    },
    watch:{},
    computed:{
        labelWidth () {
            return  100;
        },
        labelPosition () {
            return  'right';
        },
        //表格属性
        tableAttrs() {
            let tmpTableConfig = cloneDeep(this.tableConfig);
            this.$delete(tmpTableConfig,'columns');
            if(this.tableSize && this.tableSize !=''){
                tmpTableConfig['size'] = this.tableSize;
            }else{
                this.tableSize = tmpTableConfig.size;
            }
            return tmpTableConfig;
        },
        //表格事件
        tableEvent() {
            // this.table.eventModel;
        },
        //动态设置列
        tableColumns() {
            const columns = [...this.columns];
            return columns.filter(item => item.show);
        },
        offset () {
            return (this.pageNation.pageNumber - 1) * this.pageNation.pageSize;
        }
    },

    methods:{
        handleSearch () {

        },
        handleReset () {

        },
        //初始化表格列
        initTableColumns(){
            this.columns = cloneDeep(this.tableConfig.columns);
        },
        //初始化starForm编辑表单数据
        initStarFormConfig() {
            let tmpFields =[];
            let tmpColumns =[]
            this.starFormConfig =this.lodash.merge(this.starFormConfig,this.formConfig);// Object.assign({},this.starFormConfig,this.formConfig)
            this.form = pick(this.starFormConfig,Object.keys(this.form));
            this.formTitle = cloneDeep(this.starFormConfig.title);
            this.formTitleStyle = cloneDeep(this.starFormConfig.titleStyle);
            this.formStyle = cloneDeep(this.starFormConfig.formStyle);
            this.formFields = cloneDeep(this.starFormConfig.fields);

            if(this.tableConfig.columns && this.tableConfig.columns.length >0){
                tmpColumns = cloneDeep(this.tableConfig.columns);
            }
            this.primaryKey = 'id';
            tmpColumns.map(col=>{
                if(col.edit){
                    tmpFields.push({
                        dataIndex: col.key,
                        defaultValue: this.getFormData(col.validate),
                        editor: this.getEditorName(col.validate),
                        label: col.title,
                        labelIndex: "label",
                        required: col.required,
                        validate: this.getValidateType(col.validate)
                    })
                    this.formData[col.key] = this.getFormData(col.validate)
                }
                if(col.primary){
                    this.primaryKey = col.key;
                }
            })
            this.sourceFormData = cloneDeep(this.formData);
            this.formFields = cloneDeep(tmpFields);
            this.refresh=false;
            this.$nextTick(()=>{
                this.refresh=true;
            })
        },

        //初始化查询form表单数据
        initQueryFormData(){
            let tmpColumns =[]
            if(this.tableConfig.columns && this.tableConfig.columns.length >0){
                tmpColumns = cloneDeep(this.tableConfig.columns);
            }
            this.queryFormData ={};
            this.queryFormData = {};
            this.collapseFormItem =[];
            tmpColumns.map(item=>{
                if(item.filter){
                    this.queryFormData[item.key] = this.getFormData(item.validate);
                    if(this.queryFormItem.length > 1){
                        this.collapseFormItem.push({key:item.key,title:item.title,editor:this.getEditorName(item.validate)});
                    }else{
                        this.queryFormItem.push({key:item.key,title:item.title,editor:this.getEditorName(item.validate)});
                    }
                }
            })
            this.formRefresh=false;
            this.$nextTick(()=>{
                this.formRefresh=true;
            })
        },
        //获取编辑表单初始数据
        getFormData(valueType){
            let tmpData = '';
            let date = new Date();
            switch (valueType){
                case "string":
                    break;
                case "integer":
                    tmpData = 0;
                    break;
                case "float":
                    tmpData = 0.0;
                    break;
                case "boolean":
                    tmpData = false;
                    break;
                case "date":
                    let strDate = this.$Date(date).format('YYYY-MM-DD');
                    tmpData = strDate
                    break;
                case "time":
                    let strTime = this.$Date(date).format('HH:mm:ss');
                    tmpData = strTime
                    break;
                case "datetime":
                    let strDateTime = this.$Date(date).format('YYYY-MM-DD HH:mm:ss');
                    tmpData = strDateTime
                    break;
                default:
                    break;
            }
            return tmpData;
        },
        //获取编辑标签名称
        getEditorName(valueType){
            let tagName = 'input';
            switch (valueType){
                case "string":
                    break;
                case "integer":
                    tagName = 'int';
                    break;
                case "float":
                    tagName = 'number';
                    break;
                case "boolean":
                    tagName = 'check';
                    break;
                case "date":
                    tagName = 'date'
                    break;
                case "time":
                    tagName = 'time'
                    break;
                case "datetime":
                    tagName = 'datetime'
                    break;
                default:
                    break;
            }
            return tagName;
        },
        //获取验证类型
        getValidateType(valueType){
            let tagName = 'string';
            switch (valueType){
                case "string":
                    break;
                case "integer":
                    tagName = 'int';
                    break;
                case "float":
                    tagName = 'number';
                    break;
                case "boolean":
                    tagName = 'check';
                    break;
                case "date":
                    tagName = 'date';
                    break;
                case "time":
                    tagName = 'string';
                    break;
                case "datetime":
                    tagName = 'string';
                    break;
                default:
                    break;

            }
            return tagName;
        },
        //创建（添加）新表单数据
        handleOpenCreate(){
            this.formData = cloneDeep(this.sourceFormData);
            this.refresh=false;
            this.$nextTick(()=>{
                this.refresh=true;
            })
            this.form.disabled = false;
            this.drawer.type = 'new';
            this.drawer.show = true;
            this.handleInitModelForm();
        },
        //表格尺寸,可选值为 large、small、default 或者不填
        handleChangeTableSize(size){
            this.tableSize = size;
        },
        //全屏显示
        handleFullscreen(){
            this.tableFullscreen = !this.tableFullscreen;
            this.$emit('on-fullscreen', this.tableFullscreen);
        },
        //刷新数据
        handleRefresh(){
          //  this.getData();
        },
        handleClickRow(row){
            if(!this.showDetail) return;
            let sData = cloneDeep(this.handleGetData(row[this.primaryKey]));
            let keys = Object.keys(this.sourceFormData);
            keys.map(k=>{
                this.formData[k] = sData[k];
            })
            this.form.disabled = true;
            this.drawer.type = 'read';
            this.drawer.show = true;
            this.handleInitModelForm();
        },
        handleSortChange(){

        },
        handleSelect(selection, row){
            this.selectedData.push(row);
        },
        handleSelectCancel(selection, row){
            const index = this.selectedData.findIndex(item => item[this.primaryKey] === row[this.primaryKey]);
            this.selectedData.splice(index, 1);
        },
        handleSelectAll(selection){
            selection.forEach(item => {
                if (this.selectedData.findIndex(i => i[this.primaryKey] === item[this.primaryKey]) < 0) {
                    this.selectedData.push(item);
                }
            });
        },
        handleClearSelect () {
            this.selectedData = [];
        },
        handleSubmitNew(){
            this.submitting = false;
            this.drawer.show = false;
            this.$refs._frm.submit();
        },
        modelDataAddSave(data){
            if (this.submitting) return;
            this.submitting = true;
            this.$emit('addData', data);
            this.submitting = false;
        },
        modelDataEditSave(data) {
            if (this.submitting) return;
            this.submitting = true;
            let oldData = this.handleGetData(this.selectedDataId);
            if (!data[this.primaryKey]) {
                data[this.primaryKey] = oldData[this.primaryKey];
            }
            this.$emit('editData', data,oldData[this.primaryKey]);
            this.submitting = false;
        },
        // 查找单一职位信息
        handleGetData (id) {
            return this.data.find(item => item[this.primaryKey] === id);
        },
        handleEdit(id){
            this.selectedDataId = id;
            let sData = cloneDeep(this.handleGetData(id));
            let keys = Object.keys(this.sourceFormData);
            keys.map(k=>{
                this.formData[k] = sData[k];
            })
            this.formDataString = JSON.stringify(this.formData);
            this.form.disabled = false;
            this.drawer.type = 'edit';
            this.drawer.show = true;
            this.handleInitModelForm();
        },
        handleSubmitEdit(){
            this.submitting = false;
            this.drawer.show = false;
            this.$refs._frm.submit();
        },
        handleCloseEdit(){
            // 判断内容是否修改，没修改则直接关闭
            if (this.drawer.type === 'edit') {
                const editFormData = cloneDeep(this.$refs._frm.cloneData);
                const editFormDataString = JSON.stringify(editFormData);
                if (editFormDataString !== this.formDataString) {
                    return new Promise((resolve) => {
                        this.$Modal.confirm({
                            title: '关闭确认',
                            content: '您已经修改了相关信息，是否直接关闭？',
                            onOk: () => {
                                resolve();
                            }
                        });
                    });
                }
            }
        },
        // 删除
        handleDelete (id) {
            if (this.loading) return;
            this.$Modal.confirm({
                title: '删除确认',
                content: `您确认要删除当前选中的数据吗？`,
                loading: true,
                onOk: () => {
                    this.deleteModelData(id);
                }
            });
        },
        //根据职位ID删除职位
        deleteModelData(id){
            this.submitting = false;
            this.$Modal.remove();
            this.$emit('deleteData', id);
        },
        // 批量删除
        handleDeleteMultiple () {
            if (this.loading) return;
            const ids = this.selectedData.map(item => item[this.primaryKey]);
            this.$Modal.confirm({
                title: '删除确认',
                content: `您确认要批量删除所选择数据吗？`,
                loading: true,
                onOk: () => {
                    this.deleteModelDataMultiple(ids);
                }
            });
        },
        //批量删除
        deleteModelDataMultiple(ids){
            this.submitting = false;
            this.$Modal.remove();
            this.$emit('deleteBatchData', ids);
        },
        handleChangePage (page) {
            this.pageNation.pageNumber = page;
            this.getData();
        },
        handleChangePageSize(){
            this.pageNation.pageNumber = 1;
            this.pageNation.pageSize = size;
            this.getData();
        },
        handleDataSubmit(data){
            if(this.drawer.type == 'new'){
                this.modelDataAddSave(data);
            }else{
                this.modelDataEditSave(data);
            }
        },
        handleInitModelForm() {
            this.refresh =false;
            this.$nextTick(() => {
                this.refresh = true;
            });
        },
        isEmpty(obj){
            if(typeof obj == "undefined" || obj == null || obj == ""){
                return true;
            }else{
                return false;
            }
        }
    }
}
</script>
<style lang="less">
.page-form-drawer {
    &-drawer {
        &-footer {
            width: 100%;
            position: absolute;
            bottom: 0;
            left: 0;
            border-top: 1px solid #e8e8e8;
            padding: 10px 16px;
            text-align: right;
            background: #fff;
        }

        &-form {
            .ivu-input[disabled], fieldset[disabled] .ivu-input, .ivu-select-disabled .ivu-select-selection {
                background-color: #fff;
                color: inherit;
            }

            &-region {
                .i-region-transfer {
                    width: 270px;
                }

                .i-region-drop-main {
                    width: 270px !important;
                    height: 200px;
                    overflow: auto;
                    column-count: 2;

                    &-item {
                        line-height: normal;
                    }
                }
            }
        }
    }
}
</style>

